﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dao;

namespace Web.Page
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            Users_Dao dao = new Users_Dao();
            User user = new User();
            string name = this.tbName.Text.Trim();
            int res = dao.Login(name, this.tbPassword.Text, ref user);
            switch (res)
            {
                case 0:
                    this.lbResult.Text = "登录成功";
                    Session.Add("username", name);
                    Session.Add("user", user);
                    LoginOk(user);
                    
                    //Server.Transfer("Main.aspx");
                    break;

                case -1001:
                    this.lbResult.Text = "无此用户";                    
                    this.tbName.Text = "";
                    break;

                case -1002:
                    this.lbResult.Text = "密码不对";
                    this.tbPassword.Text = "";
                    break;
            }
        }

        protected void LoginOk(User user)
        {
            string name = user.Name;
            FormsAuthentication.Initialize();
            FormsAuthentication.SetAuthCookie(name, false);

            string strRole = string.Empty;
           var roles = user.Roles.ToList<Role>();
            foreach (var r in roles)
            {
                strRole += r.Name + ";";
            }

            //The AddMinutes determines how long the user will be logged in after leaving
            //the site if he doesn't log off.
            FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1,
                name, DateTime.Now,
                DateTime.Now.AddMinutes(120), false, strRole,
                FormsAuthentication.FormsCookiePath);
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,
                FormsAuthentication.Encrypt(fat)));
            Response.Redirect(FormsAuthentication.GetRedirectUrl(name, false));
        }
    }
}